<template>
  <div>
    <van-nav-bar
      title="修改密码"
      fixed
      left-arrow
      @click-left="onClickLeft"
      @click-right="onClickRight"
    >
      <template #right>
        <van-icon name="home-o" size="22" />
      </template>
    </van-nav-bar>
    <van-form @submit="onSubmit" class="myform">
      <van-field
        v-model="currentPassword"
        type="password"
        name="currentPassword"
        label="当前密码"
        placeholder="请输入当前密码"
        :rules="[{ pattern: pwdvalid, message: '请正确输入当前密码' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="新密码"
        placeholder="新密码"
        :rules="[{ pattern: pwdvalid, message: '密码不符合规范' }]"
      />
      <van-field
        v-model="repassword"
        type="password"
        name="repassword"
        label="重复密码"
        placeholder="重复密码"
        :rules="[{ validator : rePasswordVaild, message: '两次密码不一致' }]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'

export default {
  name: 'changePassword',
  data() {
    return {
      currentPassword: '',
      password: '',
      repassword: '',
      pwdvalid: /^\w{5,17}$/
    }
  },
  methods: {
    ...mapMutations(['getCookie']),
    // 头部左侧图标动作
    onClickLeft() {
      window.history.length > 1 ? this.$router.go(-1) : this.$router.push('/')
    },
    // 头部右侧图标点击动作
    onClickRight() {
      this.$router.push('/home')
    },
    rePasswordVaild() {
      return this.password === this.repassword
    },
    onSubmit() {
      this.commen.changePassword(
        { oldpwd: this.currentPassword, newpwd: this.password },
        res => {
          if (res.data.status === 200) {
            this.$dialog({ message: res.data.msg })
            window.history.length > 1
              ? this.$router.go(-1)
              : this.$router.push('/')
          } else {
            this.$dialog({ message: res.data.msg })
          }
        }
      )
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
